package com.happyscan138.makefun.Fragment;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Toast;

import com.happyscan138.makefun.BaseAdapter.main_best_lietview;
import com.happyscan138.makefun.R;
import com.happyscan138.makefun.Urls.Urls;
import com.happyscan138.makefun.adapter.main_best_adapter;
import com.happyscan138.makefun.base.LoadListView;
import com.happyscan138.makefun.base.WaitNetDataPop;
import com.happyscan138.makefun.questionDetailed;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.RequestHandle;
import com.loopj.android.http.RequestParams;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import cz.msebera.android.httpclient.Header;

import static android.content.Context.MODE_PRIVATE;
import static com.happyscan138.makefun.base.http.client;
import static com.happyscan138.makefun.base.http.params;
import static com.loopj.android.http.AsyncHttpClient.log;

/**
 * Created by Administrator on 2016/11/24.
 */

public class main_best_Fragment extends Fragment implements LoadListView.IloadListener {
    private Context mContext;
    private LoadListView main_best_listView;
    //定义一个动态数组
    private List<main_best_lietview> listData;
    //声明一个SharedPreferences对象和一个Editor对象
    private SharedPreferences preferences;
    private SharedPreferences.Editor editor;
    private String access_key;
    private Intent intent;
    private main_best_lietview data;
    private int  PROBLEM_ID_INDEX ;
    private SwipeRefreshLayout mSwipeLayout;
    private Handler handler;
    private WaitNetDataPop waitNetDataPop;
    private main_best_adapter adapter;
    private ArrayList<Integer> ID;
    //Tab用来标记集合第一个元素，是否发生变化，用来做下拉刷新
    private int Tab;
    private int IfRefresh;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view=inflater.inflate(R.layout.main_best_fragment,container,false);
        mContext = getActivity();
        client=new AsyncHttpClient();
        params=new RequestParams();
        ID=new ArrayList<Integer>();
        preferences = getActivity().getSharedPreferences("UserInfo", MODE_PRIVATE);
        access_key=preferences.getString("UserId","");
        waitNetDataPop=new WaitNetDataPop(getActivity());
        waitNetDataPop.displayPop();
        initView(view);
        getAdapterView();
        main_best_listView.setInterface(this);
        return view;
    }
    public void initView(View view) {
        main_best_listView = (LoadListView) view.findViewById(R.id.main_best_listView);
        mSwipeLayout = (SwipeRefreshLayout) view.findViewById(R.id.best_id_swipe_ly);
        mSwipeLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                params.put("page_count", "10");
                params.put("last_item_index", 0);
                RequestHandle handle = client.post(Urls.cteatQuestionBest, params, new JsonHttpResponseHandler() {
                    @Override
                    public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                        super.onSuccess(statusCode, headers, response);
                        String jsonStr = response.toString();
                        try {
                            JSONObject jsonObject = new JSONObject(jsonStr);
                            JSONArray jsonArray = jsonObject.getJSONArray("data");
                            JSONObject obj=jsonArray.getJSONObject(0);
                            IfRefresh=obj.getInt("problem_id");
                            log.e("IfRefresh",IfRefresh+"");
                            log.e("IfRefresh",Tab+"");
                            if (IfRefresh == Tab) {
                                Toast.makeText(getActivity(), "已是最新数据", Toast.LENGTH_SHORT).show();
                            }    else {
                                for (int i = 0; i < jsonArray.length(); i++) {
                                    JSONObject objectData = jsonArray.getJSONObject(i);
                                    PROBLEM_ID_INDEX=objectData.getInt("problem_id");
                                    ID.add(PROBLEM_ID_INDEX);
                                    data=new main_best_lietview();
                                    data.userID = objectData.getString("user_id");
                                    log.e("user_id", data.userID + "");
                                    data.icon = Urls.base + objectData.getString("img_path");
                                    log.e("icon", data.icon.toString());
                                    data.name = objectData.getString("nick_name");
                                    data.time = objectData.getString("create_date");
                                    data.text = objectData.getString("content");
                                    data.resourse = Urls.base + objectData.getString("resource");
                                    data.Thumb=Urls.base+objectData.getString("thumb");
                                    data.m3u8=Urls.base+objectData.getString("m3u8_file");
                                    data.viewNum = objectData.getInt("read_count");
                                    data.answerNum = objectData.getInt("replay_count");
                                    data.commentNum = i;
                                    data.goodNum = objectData.getInt("admire_count");
                                    data.problem_id = objectData.getString("problem_id");
                                    listData.add(data);

                                }
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        adapter.notifyDataSetChanged();
                    }
                });
                mSwipeLayout.setRefreshing(false);
            }
        });
    }
    public void getAdapterView() {
        params.put("page_count","10");
        params.put("last_item_index",0);
        log.e("params", params.toString());
        RequestHandle handle= client.post(Urls.cteatQuestionBest, params,new JsonHttpResponseHandler(){
            @Override
            public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                super.onSuccess(statusCode, headers, response);
                String jsonStr=response.toString();
                log.e("jsonStr",jsonStr);
                listData=new ArrayList<>();
                try {
                    JSONObject jsonObject=new JSONObject(jsonStr);
                    JSONArray jsonArray=jsonObject.getJSONArray("data");
                    for (int i=0;i<jsonArray.length();i++){
                        JSONObject objectData=jsonArray.getJSONObject(i);
                        PROBLEM_ID_INDEX=objectData.getInt("problem_id");
                        ID.add(PROBLEM_ID_INDEX);
                        log.e("ID",ID.toString());
                        Tab=ID.get(0);
                        data=new main_best_lietview();
                        data.userID=objectData.getString("user_id");
                        data.icon= Urls.base+objectData.getString("img_path");
                        data.name=objectData.getString("nick_name");
                        data.time=objectData.getString("create_date");
                        data.text=objectData.getString("content");
                        data.resourse= Urls.base+objectData.getString("resource");
                        data.Thumb=Urls.base+objectData.getString("thumb");
                        data.m3u8=Urls.base+objectData.getString("m3u8_file");
                        data.problem_id=objectData.getString("problem_id");
                        data.viewNum=objectData.getInt("read_count");
                        data.answerNum=objectData.getInt("replay_count");
                        data.commentNum=i;
                        data.goodNum=objectData.getInt("admire_count");
                        listData.add(data);

                    }
                    log.e("listData",listData.toString());
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                adapter=new main_best_adapter(getActivity(),listData,access_key,main_best_listView);
                main_best_listView.setAdapter(adapter);
                waitNetDataPop.dismiss();
                main_best_listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
                        intent =new Intent();
                        data=listData.get(position);
                        intent.putExtra("problem_id",data.problem_id);
                        intent.setClass(getActivity(),questionDetailed.class);
                        startActivity(intent);
                    }
                });
            }
            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                super.onFailure(statusCode, headers, responseString, throwable);
                log.e("responseString",responseString);

            }
        });
    }

    @Override
    public void onLoad() {
        handler = new Handler();
        handler.postDelayed(new Runnable(){
            @Override
            public void run() {
                params.put("page_count", "10");
                params.put("last_item_index", ID.get(ID.size()-1));

                log.e("params",params.toString());
                RequestHandle handle = client.post(Urls.cteatQuestionNew, params, new JsonHttpResponseHandler() {
                    @Override
                    public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                        super.onSuccess(statusCode, headers, response);
                        String jsonStr = response.toString();
                        try {
                            JSONObject jsonObject = new JSONObject(jsonStr);
                            JSONArray jsonArray = jsonObject.getJSONArray("data");
                            for (int i = 0; i < jsonArray.length(); i++) {
                                JSONObject objectData = jsonArray.getJSONObject(i);
                                PROBLEM_ID_INDEX=objectData.getInt("problem_id");
                                ID.add(PROBLEM_ID_INDEX);
                                log.e("ID",ID.toString());
                                data=new main_best_lietview();
                                data.userID = objectData.getString("user_id");
                                data.icon = Urls.base + objectData.getString("img_path");
                                data.name = objectData.getString("nick_name");
                                data.time = objectData.getString("create_date");
                                data.text = objectData.getString("content");
                                data.resourse = Urls.base + objectData.getString("resource");
                                data.Thumb=Urls.base+objectData.getString("thumb");
                                data.m3u8=Urls.base+objectData.getString("m3u8_file");
                                data.viewNum = objectData.getInt("read_count");
                                data.answerNum = objectData.getInt("replay_count");
                                data.commentNum = i;
                                data.goodNum = objectData.getInt("admire_count");
                                data.problem_id = objectData.getString("problem_id");
                                listData.add(data);
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        adapter.notifyDataSetChanged();
                    }
                });
                main_best_listView.loadComplete();
            }
        },1000);
    }
}
